//
//  InTrainingController.swift
//  DaRings
//
//  Created by 魔样科技 on 2022/11/4.
//

import Foundation
import MYModule
import CRPSmartRing
import UIKit

open class InTrainingController: ViewController {
    
    public var type: TrainingType = .unknown
    
    public var goalType: TrainingTypeContent?
    
   
    public var isContinueFromConnect = false
    
    public var startTime: Int = 0
    
    /// 是否断连
    public var isDisconnected: Bool = false
    
    
    open var viewModel: InTrainingViewModel? {
        didSet {
            collectionView.reloadData()
        }
    }
    
    open var trainAction: TrainingAction = .training {
        didSet {
            switch trainAction {
            //2023年01月29日11:59:33 因为如果使用同一个timer的话，会在点继续的时候马上+1，所以暂停就销毁，继续就创建赋值
            case .pause:
                removeTime()
                self.updateTrainingState(2)
            case .locked:
                break
            case .training:
                addTime()
                self.updateTrainingState(1)
            case .endTraining:
                //此处不使用removeTime()是因为停止，一定是在暂停以后才会有停止按钮的，点击暂停以后就会调用removeTime()，这里就不用重复调用了；
                //此处不更新数据库的trainingState是因为点击停止按钮以后，还会做很多判断，在判断那里修改
//                removeTime()
//                self.viewModel?.trainingModel?.trainingState = 0
//                self.viewModel?.trainingModel?.updateData()
                break
            }
        }
    }
    
    /// 在结束锻炼前的弹窗样式
    public var alertType: AlertType = .none
    
    public var startStepDetail = ActivityModel()
    
    public var beforeDetail: ActivityModel?
    
    public lazy var collectionView: CollectionView = {
        let collectionView = CollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isScrollEnabled = false
        collectionView.automaticallyContentSize = true
        return collectionView
    }()
    
    public lazy var layout: UICollectionViewFlowLayout = {
        
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = CGSize.zero
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = UIEdgeInsets.zero
        
        layout.scrollDirection = .vertical
        
        return layout
    }()
    
    public var time: Timer?
    
    // 当前计数时间
    public var time_second: Int = 0
    
    // 上一次记录时长时间
    public var last_save_second: Int = 0
    
    // 一阶段的配速计算距离
    public var paceInDistance = 0
    // 一阶段的配速计算时长
    public var paceInTime = 0
    // 一阶段的配速计算 时间 >= 2
    public var paceInRecordSecond = 0
    
    
    open var goalSettingType: CRPSmartRing.CRPTrainingGoalType {
        return goalType?.goalType ?? .none
        
    }
    
    open var goal: Int {
        
        return Int(viewModel?.trainingModel?.goal ?? 0)
    }
    
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavigationBar()
        
        // 查询 一开始的步数，需要减去
        if let last = ActivityModel.day(date: Date()) {
            startStepDetail = last
        }
        
        if type != .unknown && viewModel == nil {
            let viewModel = InTrainingViewModel(type: type, golaType: goalType, startTime: self.startTime)
            self.viewModel = viewModel

//            if let trainingModel = viewModel.trainingModel {
//                if trainingModel.step != 0 {
//                    startStepDetail.step = trainingModel.step
//                }
//                if trainingModel.kcal != 0 {
//                    startStepDetail.calorie = trainingModel.kcal
//                }
//
//                if trainingModel.distance != 0 {
//                    startStepDetail.distance = trainingModel.distance
//                }
//
//            }

        }

        addTime()
        
        reloadUIWithTrainingState()
        
    }
    
    open func setNavigationBar() {
        self.navigation.item.leftBarButtonItem = nil
        navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateUI(noti:)), name: .kUpdateUINotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(deviceStateChange(noti:)), name: .kDeviceStateNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(bluetoothStateChange(noti:)), name: .kBluetoothStateNotification, object: nil)
        
    }
    
    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        removeTime()
        
        NotificationCenter.default.removeObserver(self)

    }
    
    open override func makeUI() {
        super.makeUI()
        
        collectionView.register(InTrainingItemCollectionCell.self, forCellWithReuseIdentifier: InTrainingItemCollectionCell.reuseIdentifier)
        collectionView.register(InTrainingTargetCollectionCell.self, forCellWithReuseIdentifier: InTrainingTargetCollectionCell.reuseIdentifier)
        collectionView.register(InTrainingProgressCollectionCell.self, forCellWithReuseIdentifier: InTrainingProgressCollectionCell.reuseIdentifier)
        
        collectionView.dataSource = self
        collectionView.delegate = self
        
        self.view.addSubview(collectionView)
        
        self.view.addSubview(self.continueButton)
        self.view.addSubview(self.finishButton)
        self.view.addSubview(self.pauseButton)
        self.view.addSubview(self.lockButton)
        self.view.addSubview(self.unlockButton)
        
        let top = UIApplication.shared.statusBarFrame.height + self.navigation.bar.height
        
        collectionView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(top + 76)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(unlockButton.snp.top)
        }
    
        self.unlockButton.snp.makeConstraints { make in
            make.bottom.equalTo(-80)
            make.width.height.equalTo(100)
            make.centerX.equalToSuperview()
        }
        
        self.lockButton.snp.makeConstraints { make in
            make.centerY.equalTo(self.unlockButton.snp.centerY)
            make.leading.equalTo(62)
            make.width.height.equalTo(100)
        }
       
        self.pauseButton.snp.makeConstraints { make in
            make.centerY.equalTo(self.unlockButton.snp.centerY)
            make.width.height.equalTo(100)
            make.trailing.equalTo(-62)
        }
        
        
        self.finishButton.snp.makeConstraints { make in
            make.centerY.equalTo(self.unlockButton.snp.centerY)
            make.leading.equalTo(62)
            make.width.height.equalTo(100)
        }
        
        
        self.continueButton.snp.makeConstraints { make in
            make.centerY.equalTo(self.unlockButton.snp.centerY)
            make.width.height.equalTo(100)
            make.trailing.equalTo(-62)
        }
        
        
        self.navigation.bar.backgroundColor = UIColor.background
        self.changeTrainingState(.didStart)
        #if DEBUG
        //TODO: - 测试包用于查看戒指连接状态
        self.view.addSubview(self.bleStateLabel)
        self.bleStateLabel.snp.makeConstraints { make in
            make.trailing.equalTo(-10)
            make.top.equalTo(top)
            make.height.equalTo(20)
            make.leading.equalTo(10)
        }
        self.showBleState(state: BluetoothManager.shared.bluetoothState)
        
        self.view.addSubview(self.connectStateLabel)
        self.connectStateLabel.snp.makeConstraints { make in
            make.trailing.equalTo(-10)
            make.top.equalTo(self.bleStateLabel.snp.bottom).offset(10)
            make.height.equalTo(20)
            make.leading.equalTo(10)
        }
        self.showDeviceState(state: BluetoothManager.shared.deviceState)
        #endif
    }
    
    open override func bindViewModel() {
        super.bindViewModel()
        

        self.lockButton.rx.tap.subscribe { [weak self] _ in
            guard let self = self else { return }
            
            self.trainAction = .locked
            self.changeTrainingState(.didLock)
            
        }.disposed(by: rx.disposeBag)
        
        self.unlockButton.actionWithClosure { [weak self] (state) in
            guard let self = self else { return }
            switch state {
            case .End:
                self.changeTrainingState(.didUnlock)
            default: break
            }
        }
        
        self.pauseButton.rx.tap.subscribe(onNext: { [weak self] in
            guard let self = self else { return }
            self.trainAction = .pause
            BluetoothManager.shared.setTraining(state: .pause, type: self.goalSettingType, goal: self.goal)
            
            self.clickedPause()
            
            
        }).disposed(by: rx.disposeBag)
        
        self.continueButton.rx.tap.subscribe(onNext: { [weak self] in
            guard let self = self else { return }
            
            self.trainAction = .training
            BluetoothManager.shared.setTraining(state: .proceed, type: self.goalSettingType, goal: self.goal)

            self.clickedContinue()
        }).disposed(by: rx.disposeBag)
        
        self.finishButton.rx.tap.subscribe(onNext: { [weak self] in
            guard let self = self else { return }
            
            self.finish()
            
        }).disposed(by: rx.disposeBag)
        
//        NotificationCenter.default.rx.notification(Notification.Name.kDeviceStateNotification).take(until: self.rx.deallocated).subscribe(onNext:{[weak self] notification in
//            guard let self = self else { return }
//            guard let result = notification.userInfo as? [String: Any] else { return}
//            guard let state = result["result"] as? CRPState else { return }
//            guard state == .connected else {
//                self.isDisconnected = true
//                return
//            }
//            self.isDisconnected = false
//
//        }).disposed(by: rx.disposeBag)
//
//        NotificationCenter.default.rx.notification(Notification.Name.kBluetoothStateNotification).take(until: self.rx.deallocated).subscribe(onNext:{[weak self] notification in
//            guard let self = self else { return }
//            guard let result = notification.userInfo as? [String: Any] else { return}
//            guard let state = result["result"] as? CRPBluetoothState else { return }
//            guard state == .poweredOn else {
//                self.isDisconnected = true
//                return
//            }
//
//        }).disposed(by: rx.disposeBag)
    }
    
    private func reloadUIWithTrainingState() {
        if self.viewModel?.trainingModel?.endTime == 0 && self.viewModel?.trainingModel?.trainingState == 0 {
            self.updateTrainingState(1)
        }
        
        switch self.viewModel?.trainingModel?.trainingState {
        case 1:
            self.clickedContinue()
            break
        case 0:
            break
        case 2:
            self.clickedPause()
            break

        default:
            self.clickedContinue()
            break

        }
    }
    
    private func updateTrainingState(_ state: Int) {
        self.viewModel?.trainingModel?.trainingState = state
        self.viewModel?.trainingModel?.updateData()
    }
    
    /// 这个方法是用于运动中断连，然后重连后获取了数据同步到数据库，然后需要更新当前页面的运动数据
    public func reloadTrainingModel() {
        guard let trainModel = self.viewModel?.trainingModel else {
            return
        }
        self.viewModel?.trainingModel = TrainingModel.model(of: trainModel.type, startTime: trainModel.startTime)
        
        if trainModel.trainingState == 0 && trainModel.endTime != 0 {
            pushtoDetailController()
            return
        }
    }
    
    /// 将要去详情页
    open func VerifyTrainingModel() {

        updateAlertType()
        
        if alertType == .none {
            return
        }
        
        willFinishTrainingAlertController(with: alertType) {[weak self] in
                
            guard let self = self else {
                return
            }
            
            if self.alertType == .finshTraining {
                self.updateTrainingList()
                self.pushtoDetailController()
            } else {
                self.viewModel?.trainingModel?.delete()
                self.navigationController?.popToRootViewController(animated: true)
            }
        }
    }
    
    /// 去详情页
    open func pushtoDetailController() {
        
        guard let trainingModel = viewModel?.trainingModel else { return }
        
        let newTrainingModel = TrainingModel.last(type: trainingModel.type, trainingModel.goalType, startTime: self.startTime)
        viewModel?.trainingModel = newTrainingModel
    
        // 去详情页
        let vc = TrainingDetailViewController()
        vc.achievement = trainingModel.achievement
        
        if let trainingModel = newTrainingModel {
            let viewModel = TrainingDetailViewModel(trainModel: trainingModel)
            vc.viewModel = viewModel
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    open func updateTrainingList() {
        
        // 同步运动列表
        BluetoothManager.shared.getTrainingtRecordList()
        
    }
    
    
    open func updateAlertType() {
        
        if alertType == .none {
            if time_second < 60 {
                alertType = .lessOneMinute
                return
            }
            
            if let trainingModel = viewModel?.trainingModel {
                
                if self.isDisconnected == true {
                    UIAlertController.showOkAlert(title: "dialog_ble_disconnected_when_stop_content".language, message: "", in: self) { [weak self] in
                        guard let self = self else { return }
                        // 同步 列表指令
                        self.trainAction = .endTraining
                        self.updateTrainingState(0)
                        self.viewModel?.saveData()
                        BluetoothManager.shared.setTraining(state: .end, type: self.goalSettingType, goal: self.goal)
                        self.updateTrainingList()
                        self.pushtoDetailController()
                    }
                    self.alertType = .none
                    return
                }
                
                if type.contents.contains(.distance) {
                    
                    if trainingModel.distance <= 0 {
                        alertType = .littleData
                        return
                    }
                    
                } else {
                    
                    if trainingModel.kcal <= 0 {
                        alertType = .littleData
                        return
                    }
                    
                }
            }
            
            // 到最后都不是异常情况，就是正常的要结束运动
            if alertType != .lessOneMinute && alertType != .littleData {
                alertType = .finshTraining
                return
            }
        }
    }
    

    
    
    /// 结束锻炼之前弹窗
    /// - Parameter alertType: 弹窗类型
    open func willFinishTrainingAlertController(with alertType: AlertType, confirm: (() ->Void)?) {
        
        alertType.showAlert {[weak self] in
            
            guard let self = self else { return }
            
            self.trainAction = .endTraining
            self.updateTrainingState(0)
            BluetoothManager.shared.setTraining(state: .end, type: self.goalSettingType, goal: self.goal)
            self.viewModel?.saveData()
            confirm?()
            
        } cancel: {
            self.alertType = .none
        }
    }
    

    private func changeTrainingState(_ state: TrainingState) {
        switch state {
        case .didStart, .didUnlock, .didContinue:
            self.lockButton.isHidden = false
            self.pauseButton.isHidden = false
            self.unlockButton.isHidden = true
            self.continueButton.isHidden = true
            self.finishButton.isHidden = true
        case .didPause:
            self.lockButton.isHidden = true
            self.pauseButton.isHidden = true
            self.unlockButton.isHidden = true
            self.continueButton.isHidden = false
            self.finishButton.isHidden = false
        case .didLock:
            self.lockButton.isHidden = true
            self.pauseButton.isHidden = true
            self.unlockButton.isHidden = false
            self.continueButton.isHidden = true
            self.finishButton.isHidden = true
        case .didFinish:
            
            self.VerifyTrainingModel()
                    
        }
    }
    
    private func showAlertWhenConnected() {
        if self.isDisconnected == false {
            UIAlertController.showAlertOk(title: "", message: "dialog_training_disconnected_may_inaccurate_data".language, in: self)
            self.isDisconnected = true
        }
    }
    
    //MARK: - 定时器
    open func addTime() {
        if self.time == nil && self.trainAction == .training {
            let time = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: {[weak self] _ in
                guard let self = self else { return }
                self.time_second += 1
                self.viewModel?.updateTime(self.time_second)
                self.collectionView.reloadData()
            })
            
            RunLoop.current.add(time, forMode: .common)
            self.time = time
        }
    }
    
    open func removeTime() {
        if self.time != nil {
            time?.invalidate()
            time = nil
        }
    }
    
    //MARK: - 通知响应
    @objc open func updateStepAndKcal(noti: Notification) {
        if self.trainAction == .pause {
            return
        }
        
        // 获取最后一个detail的数据
        guard let activityModel = ActivityModel.day(date: Date()) else {
            return
        }
        var intervalDistance = activityModel.distance - startStepDetail.distance
        if intervalDistance < 0 {
            intervalDistance = 0
        }
        guard let trainingModel = viewModel?.trainingModel else {
            return
        }
        
        let paceTime = activityModel.time  - startStepDetail.time
        log.debug("距离是：\(activityModel.distance)----\(startStepDetail.distance)-----\(intervalDistance)")
        trainingModel.distance = trainingModel.distance + intervalDistance
        viewModel?.updateDistance(trainingModel.distance)
         
        var intervalStep = activityModel.step - startStepDetail.step
        if intervalStep < 0 {
            intervalStep = 0
        }
        trainingModel.step = trainingModel.step + intervalStep
        viewModel?.updateStep(trainingModel.step)
        
        var intervalCalorie = activityModel.calorie - startStepDetail.calorie
        if intervalCalorie < 0 {
            intervalCalorie = 0
        }
        trainingModel.kcal = trainingModel.kcal + intervalCalorie
        viewModel?.updateCalorise(trainingModel.kcal)
        
        viewModel?.trainingModel?.updateData()
        let time = time_second - last_save_second + paceInRecordSecond
//        viewModel?.updateTime(time)
        
        // 更新配速
        if time < 2 {
            paceInDistance += intervalDistance
            paceInTime += paceTime
            paceInRecordSecond += time
        } else {
            viewModel?.updatePace(paceInDistance, seconds: paceInTime)
            paceInDistance = 0
            paceInTime = 0
            paceInRecordSecond = 0
        }
        
        last_save_second = time_second
        self.beforeDetail = activityModel
        collectionView.reloadData()
        
        startStepDetail = activityModel
    }
    
    @objc open func updateHeart(noti: Notification) {
        if self.trainAction == .pause {
            return
        }
        
        guard let dict = noti.userInfo as? [String: Any], let model = dict["result"] as? ReceiveRealTimeHeartRateModel else {
            return
        }
        
        viewModel?.updateHeartRate(model.heartRate)
        collectionView.reloadData()
        
        /// 心率预警弹窗
        BluetoothResponder.shared.heartRateMaxAlert(model.heartRate)
    }
    
    
    @objc open func updateUI(noti: Notification) {
        
        guard let dict = noti.userInfo as? [String: Any], let type = dict["type"] as? NotifactionType else { return }
        
        switch type {
            
        case .deviceState, .bluetoothState:
            //TODO: 2023年02月15日19:31:13此处的断连按钮不可点击并置灰逻辑与新增的断连弹窗并下次连接成功结束的逻辑相悖，因此删除
            break
       
        case .activity:
            
            updateStepAndKcal(noti: noti)
            break
            
        case .realTimeHeartRate:
            
            updateHeart(noti: noti)
            
            break
        case .sportState:
            
//            sportStateChange(noti: noti)
            
            break
            
        case .sportList:
            
            break
            
        default:
            break
            
        }
        
    }
    
    @objc open func deviceStateChange(noti: Notification) {
        guard let result = noti.userInfo as? [String: Any] else { return }
        guard let state = result["result"] as? CRPState else { return }
        
        self.showDeviceState(state: state)
        
        guard state == .connected else {
            self.showAlertWhenConnected()
            return
        }
        self.isDisconnected = false
    }
    
    @objc open func bluetoothStateChange(noti: Notification) {
        guard let result = noti.userInfo as? [String: Any] else { return}
        guard let state = result["result"] as? CRPBluetoothState else { return }
        
        self.showBleState(state: state)
        
        guard state == .poweredOn else {
            self.showAlertWhenConnected()
            return
        }
    }
    
    // TODO: - 测试用
    private func showBleState(state: CRPSmartRing.CRPBluetoothState) {
        switch state{
        case .poweredOn:
            self.bleStateLabel.text = "蓝牙已打开"
        case .poweredOff:
            self.bleStateLabel.text = "ble_disable".language
            self.connectStateLabel.text = "ble_disconnected".language
        default:
            self.bleStateLabel.text = "蓝牙已打开".language
        }
    }
    
    private func showDeviceState(state: CRPSmartRing.CRPState) {
        switch state{
        case .connected:
            self.connectStateLabel.text = "ble_connected".language
        case .disconnected:
            self.connectStateLabel.text = "ble_disconnected".language
        case .connecting:
            self.connectStateLabel.text = "ble_connecting".language
        default:
            self.connectStateLabel.text = "ble_connecting".language
        }
    }
    
//    @objc func
//    sportStateChange(noti: Notification) {
//
//        guard let dict = noti.userInfo as? [String: Any], let type = dict["result"] as? CRPSmartRing.CRPTrainingType else { return }
//
//        switch type {
//
//        case .pause:
//            // 开始
//            clickedPause()
//            break
//
//        case .proceed:
//            // 继续
//            self.clickedContinue()
//            break
//
//        case .end:
//            // 结束
//            finish()
//            break
//
//        default:
//            break
//        }
//    }
    
    //MARK: - 点击事件
    open func clickedPause() {
        trainAction = .pause
        self.changeTrainingState(.didPause)
    }
    
    open func clickedContinue() {
        trainAction = .training
        self.changeTrainingState(.didContinue)
    }
    
    open func finish() {
        // 去详情/无记录退出
        self.trainAction = .endTraining
        
        self.changeTrainingState(.didFinish)
    }
    
    
    
    //MARK: - lazy load -
    private lazy var lockButton: Button = {
        let button = Button()
        button.setTitle("gps_training_lock".language, for: .normal)
        button.titleLabel?.font = Fonts.boldSystemFont(ofSize: 18)
        button.setTitleColor(UIColor.assist_222222, for: .normal)
        button.layer.borderColor = UIColor.assist_EEEEEE.cgColor
        button.layer.borderWidth = 4
        button.layer.cornerRadius = 50
        return button
    }()
    
    private lazy var unlockButton: GPSTrainingLDPressButton = {
        let button = GPSTrainingLDPressButton()
        button.setTitle("gps_training_unlock".language, for: .normal)
        button.titleLabel?.font = Fonts.boldSystemFont(ofSize: 18)
        button.setTitleColor(UIColor.assist_222222, for: .normal)
        button.layer.borderColor = UIColor.assist_EEEEEE.cgColor
        button.progressColor = type.tintColor
        button.layer.borderWidth = 4
        button.layer.cornerRadius = 50
        return button
    }()
    
    private lazy var pauseButton: Button = {
        let button = Button()
        button.setTitle("gps_training_pause".language, for: .normal)
        button.titleLabel?.font = Fonts.boldSystemFont(ofSize: 18)
        button.setTitleColor(UIColor.assist_FFFFFF, for: .normal)
        button.layer.cornerRadius = 50
        button.layer.masksToBounds = true
        button.backgroundColor = UIColor.Training.theme
        
        
     
        return button
    }()
    
    private lazy var continueButton: Button = {
        let button = Button()
        button.setTitle("gps_training_continue".language, for: .normal)
        button.titleLabel?.font = Fonts.boldSystemFont(ofSize: 18)
        button.setTitleColor(UIColor.assist_FFFFFF, for: .normal)
        button.layer.cornerRadius = 50
        button.layer.masksToBounds = true
        button.backgroundColor = UIColor.Training.theme
        return button
    }()
    
    private lazy var finishButton: Button = {
        let button = Button()
        button.setTitle("gps_training_finish".language, for: .normal)
        button.titleLabel?.font = Fonts.boldSystemFont(ofSize: 18)
        button.setTitleColor(UIColor.assist_FFFFFF, for: .normal)
        button.layer.cornerRadius = 50
        button.layer.masksToBounds = true
        button.backgroundColor = UIColor.Training.finish
        return button
    }()
    
    private lazy var bleStateLabel: Label = {
        let label = Label()
        label.font = .systemFont(ofSize: 14)
        label.textColor = UIColor.theme
        label.textAlignment = .right
        return label
    }()
    
    private lazy var connectStateLabel: Label = {
        let label = Label()
        label.font = .systemFont(ofSize: 14)
        label.textColor = .init(hex: "FF2E29")
        label.textAlignment = .right
        return label
    }()
    
}

extension InTrainingController: UICollectionViewDataSource {
    
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return 3
        
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if section == 0 {
            return 1
        }
        if section == 1 {
            return viewModel?.model?.targetItem?.progress == nil ? 0 : 1
        }
        
        return viewModel?.model?.items.count ?? 0
        
    }
    
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if indexPath.section == 0 {
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: InTrainingTargetCollectionCell.reuseIdentifier, for: indexPath) as! InTrainingTargetCollectionCell
            
            cell.model = viewModel?.model
            
            return cell
            
        }
        
        if indexPath.section == 1 {
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: InTrainingProgressCollectionCell.reuseIdentifier, for: indexPath) as! InTrainingProgressCollectionCell
            
            cell.model = viewModel?.model
            
            return cell
            
        }
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: InTrainingItemCollectionCell.reuseIdentifier, for: indexPath) as! InTrainingItemCollectionCell
        
        cell.model = viewModel?.model?.items[indexPath.item]
        if viewModel?.model?.items.count == 3 {
            cell.line.isHidden = indexPath.item == 2
        } else {
            cell.line.isHidden = indexPath.item%2 != 0
        }
        return cell
       
    }
    
}

extension InTrainingController: UICollectionViewDelegateFlowLayout {
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        
        if section == 0 {
            return UIEdgeInsets.zero
        }
        
        if section == 1 {
            let top: CGFloat = viewModel?.model?.targetItem?.progress == nil ? 0 : 24
            return UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0)
        }
        
        let top: CGFloat = viewModel?.model?.targetItem?.progress == nil ? 59 : 31
        return UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0)        
    }
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        if indexPath.section == 0 {
            let height: CGFloat = viewModel?.model?.viceItem == nil ? 84.0 : 134.0
            return CGSize(width: UIScreen.main.bounds.width, height: height)
        }
        
        if indexPath.section == 1 {
            return CGSize(width: UIScreen.main.bounds.width - 46 * 2, height: 8)
        }
        
        guard let count = viewModel?.model?.items.count else {
            return CGSize.zero
        }
        
        var width = UIScreen.main.bounds.width/3.0
        if count%2 == 0 {
            width = UIScreen.main.bounds.width/2.0
        }
        return CGSize(width: width, height: 70)
        
    }

}


extension InTrainingController {
    
    public enum TrainingAction: Int, CaseIterable {
        
        case endTraining = 0
        case training = 1
        case pause = 2
        case locked = 3
        
        
    }
    
   public enum TrainingState {
        case didStart
        case didPause
        case didLock
        case didUnlock
        case didContinue
        case didFinish
    }
    
    public enum AlertType {
        
        /// 无弹窗
        case none
        
        /// 小于一分钟
        case lessOneMinute
        
        /// 数据过少
        case littleData
        
        /// 退出保存
        case finshTraining
        
        public var title: String {
            
            switch self {
            case .none:
                return ""
            case .lessOneMinute:
                return "training_end_less_than_dialog_title".language
            case .littleData:
                return "training_little_data_dialog_title".language
                
            case .finshTraining:
                return "training_end_dialog_title".language
            }
            
        }
        
        public var content: String {
            
            switch self {
                
            case .finshTraining:
                return "training_end_dialog_content".language
                
            default:
                return ""
            }
        }
        
        
        /// 显示弹窗
        public func showAlert(confirm: (() ->Void)?, cancel: (() ->Void)?) {
            
            if self == .none {
                return
            }
            
            UIAlertController.showConfirm(title: title, message: content) { _ in
                confirm?()
            } cancel: {
                cancel?()
            }

   
        }
        
    
    }
}
